package com.erp.framework.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Properties;

import com.erp.framework.SimpleConstants;

public class OsEnvUtil implements SimpleConstants {
    public static Properties getEnvVars() {
        Properties envVars = new Properties();
        try {
            Process p = null;
            Runtime r = Runtime.getRuntime();
            String OS = System.getProperty("os.name").toLowerCase();
            // System.out.println(OS);
            if (OS.indexOf("windows 9") > -1) {
                p = r.exec("command.com /c set");
            } else if ((OS.indexOf("nt") > -1) || (OS.indexOf("windows 2000") > -1) || (OS.indexOf("windows xp") > -1)) {
                // thanks to JuanFran for the xp fix!
                p = r.exec("cmd.exe /c set");
            } else {
                // our last hope, we assume Unix (thanks to H. Ware for the fix)
                p = r.exec("env");
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                int idx = line.indexOf('=');
                String key = line.substring(0, idx);
                String value = line.substring(idx + 1);
                envVars.setProperty(key, value);
                // System.out.println( key + " = " + value );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return envVars;
    }

    public static void displaySystemEnvVars() {
        Properties prop = System.getProperties();
        Enumeration enum = prop.keys();
        while (enum.hasMoreElements()) {
            String key = (String) enum.nextElement();
            String value = prop.getProperty(key);
            System.out.println(key + "=" + value);
        }
    }

    public static String getSystemEnvVars(String envVarName) {
        Properties prop = System.getProperties();
        return prop.getProperty(envVarName);
    }

    public static String getUserEnvVars(String envVarName) {
        Properties p = OsEnvUtil.getEnvVars();
        return p.getProperty(envVarName);
    }

    public static String getSysLangFromEnv() {
        String sysLang = OsEnvUtil.getUserEnvVars(OS_ENV_VAR_SYS_LANG);
        if ((sysLang == null) || (sysLang.equals(""))) {
            sysLang = LANG_DEFAULT;
        }
        return sysLang;
    }

}
